﻿using KhoaLuan.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace KhoaLuan.Areas.Admin.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/Admin/
        public ApplicationDbContext db = new ApplicationDbContext();
        public UserManager<ApplicationUser> UserManager { get; private set; }

        public AdminController()
        {
            UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
        }
        
        public ActionResult Index()
        {
            return View();
        }
        //
        // GET: /Admin/Login
        public ActionResult Login(String Authenticate = null, String Authorize = null, String Logoff = null)
        {
            if (Authenticate != null)
            {
                ModelState.AddModelError("", "Bạn chưa đăng nhập !");
            }
            if (Authorize != null)
            {
                ModelState.AddModelError("", "Bạn không có quyền !");
            }
            if (Logoff != null)
            {
                AuthenticationManager.SignOut();
                ModelState.AddModelError("", "Đăng xuất thành công !");
            }
            return View();
        }

        //
        // POST: /Admin/Login
        [HttpPost]
        public ActionResult Login(String UserName, String Password)
        {
            var user = UserManager.Find(UserName, Password);
            if (user != null)
            {
                SignIn(user, false);
                ModelState.AddModelError("", "Đăng nhập thành công !");
            }
            else
            {
                ModelState.AddModelError("", "Sai thông tin đăng nhập !");
            }
            return RedirectToAction("Index", "Home");
        }



        //
        // GET: /Admin/Logoff
        [Authorize]
        public ActionResult LogOff()
        {
            AuthenticationManager.SignOut();
            return RedirectToAction("Index", "Home");
        }


        public IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }

        public void SignIn(ApplicationUser user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
        }
	}
}